package com.lunago.agent.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lunago.agent.constant.JsonResult;
import com.lunago.agent.constant.ServiceCode;
import com.lunago.agent.ex.ServiceException;
import com.lunago.agent.jwt.JwtPayLoad;
import com.lunago.agent.mapper.PromptRoleMapper;
import com.lunago.agent.pojo.dto.ChatQuery;
import com.lunago.agent.pojo.entity.ChatRecord;
import com.lunago.agent.pojo.entity.PromptRole;
import com.lunago.agent.pojo.entity.UserGems;
import com.lunago.agent.service.ChatRecordService;
import com.lunago.agent.service.UserGemsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/aichat")
@Api(tags = "查询常见话题")
public class ChatController {
    public static final String GPT4 = "gpt-4o";
    public static final String GPT4O_MINI = "gpt-4o-mini";
    public static final int gem_cost = 2;

    @Value("${gpt-api-key}")
    private String apiKey;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserGemsService userGemsService;
    @Autowired
    private PromptRoleMapper promptRoleMapper;
    @Autowired
    private ChatRecordService chatRecordService;

    @PostMapping("/records")
    public JsonResult records(@AuthenticationPrincipal JwtPayLoad payload) {
        Long userId = payload.getUserId();
        return JsonResult.ok(chatRecordService.queryAllLimit(userId, 0));
    }

    @PostMapping("/oracle")
    public JsonResult oracle(@org.springframework.web.bind.annotation.RequestBody ChatQuery chatQuery, @AuthenticationPrincipal JwtPayLoad payload) {
        // 验证点数
        Long userId = payload.getUserId();
        UserGems userGems = userGemsService.queryMyGems(userId);
        if (userGems.getGems() < gem_cost) {
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, "点数不足");
        }

        // 构造 System Prompt
        PromptRole promptRole = promptRoleMapper.selectByName(chatQuery.getRoleName());
        String SystemContent = promptRole.getRoleContent();
        JSONArray promptArray = new JSONArray();
        JSONObject systemPromptObject = new JSONObject();
        systemPromptObject.put("role", "system");
        systemPromptObject.put("content", SystemContent);
        promptArray.add(systemPromptObject);

        // 构造 User Prompt
        List<ChatRecord> chatRecords = chatRecordService.queryAllLimit(userId, 10);
        Collections.reverse(chatRecords);
        for (ChatRecord chatRecord : chatRecords) {
            JSONObject userPromptObject = new JSONObject();
            if (chatRecord.getOwner().equals("user")) {
                userPromptObject.put("role", "user");
                userPromptObject.put("content", chatRecord.getContent());
            }else {
                userPromptObject.put("role", "assistant");
                userPromptObject.put("content", chatRecord.getContent());
            }
            promptArray.add(userPromptObject);
        }
        // 当前用户
        JSONObject userPromptObject = new JSONObject();
        userPromptObject.put("role", "user");
        userPromptObject.put("content", chatQuery.getContent());
        promptArray.add(userPromptObject);

        JSONObject requestObject = new JSONObject();
        requestObject.put("model", GPT4);
        requestObject.put("messages", promptArray);
        System.out.println("----------------------------------------------------------------------------------------------------");
        System.out.println(promptArray);

        // 发送请求
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey); // 替换为你的 API 密钥
        headers.set("Content-Type", "application/json");
        // 创建 HttpEntity 包装请求体和请求头
        HttpEntity<String> entity = new HttpEntity<>(requestObject.toString(), headers);
        // 发送 POST 请求
        String url = "https://api.openai.com/v1/chat/completions";
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        if (response.getStatusCode().is2xxSuccessful()) {
            String returnContent = response.getBody();
            userGemsService.consumeGems(userId, gem_cost);
            JSONObject jsonObject = JSONObject.parseObject(returnContent);
            JSONObject choices0 = jsonObject.getJSONArray("choices").getJSONObject(0);
            userGems = userGemsService.queryMyGems(userId);
            int gems = userGems.getGems();
            Map<String, Object> resultMap = new HashMap<>();
            String reply = choices0.getJSONObject("message").get("content").toString();
            resultMap.put("reply", reply);
            resultMap.put("gems", gems);

            // 存入聊天记录
            chatRecordService.save(userId, chatQuery.getContent(), "user");
            chatRecordService.save(userId, reply, "gpt");
            return JsonResult.ok(resultMap);
        }
        return JsonResult.fail(ServiceCode.ERROR_UNKNOWN, "内核错误");
    }

    @PostMapping("/oracle3")
    @Deprecated
    public JsonResult oracle3(@org.springframework.web.bind.annotation.RequestBody ChatQuery chatQuery, @AuthenticationPrincipal JwtPayLoad payload) {
        Long userId = payload.getUserId();
        UserGems userGems = userGemsService.queryMyGems(userId);
        if (userGems.getGems() < gem_cost) {
            throw new ServiceException(ServiceCode.ERROR_FORBIDDEN, "点数不足");
        }

        OkHttpClient client = new OkHttpClient();

        /* role system */
        PromptRole promptRole = promptRoleMapper.selectByName(chatQuery.getRoleName());
        String SystemContent = promptRole.getRoleContent();

        /* role user */
//        String content = chatQuery.getContent();
//        if (null != chatQuery.getTopicID()) {
//            Topic condition = new Topic();
//            condition.setId(chatQuery.getTopicID());
//            Topic topic = topicMapper.selectTopicByID(condition);
//            content = topic + content;
//        }

        JSONArray promptArray = new JSONArray();
        JSONObject systemPromptObject = new JSONObject();
        systemPromptObject.put("role", "system");
        systemPromptObject.put("content", SystemContent);
        JSONObject userPromptObject = new JSONObject();
        userPromptObject.put("role", "user");
        userPromptObject.put("content", chatQuery.getContent());
        promptArray.add(userPromptObject);
        promptArray.add(systemPromptObject);
        JSONObject requestObject = new JSONObject();
        requestObject.put("model", GPT4);
        requestObject.put("messages", promptArray);
        // System.out.println(requestObject.toString() + "----------");

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(requestObject.toJSONString(), JSON);

        Request request = new Request.Builder()
                .url("https://api.openai.com/v1/chat/completions")
                .header("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        String returnContent;
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                userGemsService.consumeGems(userId, gem_cost);
                returnContent = response.body().string();
//                System.out.println(response.body().string());
//                System.out.println(returnContent);
                JSONObject jsonObject = JSONObject.parseObject(returnContent);
                JSONObject choices0 = jsonObject.getJSONArray("choices").getJSONObject(0);
                userGems = userGemsService.queryMyGems(userId);
                int gems = userGems.getGems();
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("reply", choices0.getJSONObject("message").get("content"));
                resultMap.put("gems", gems);
                return JsonResult.ok(resultMap);
            } else {
                log.error("Request failed: " + response.code());
                return JsonResult.fail(ServiceCode.ERROR_UNKNOWN, "聊天错误");
//                System.err.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            log.error("内核通信错误", e);
            return JsonResult.fail(ServiceCode.ERROR_UNKNOWN, "内核通信错误");
        }
    }
}
